from asyncio import get_event_loop, gather
from asyncio.exceptions import TimeoutError
from re import match
from time import time

from aiohttp import ClientSession
from aiohttp.client_exceptions import ClientConnectionError

count = 0


class AlibbPoll:

    def __init__(self):
        self.__session = ClientSession()
        self.__csrf_token = None
        self.status = True

    @staticmethod
    def match_token(content):
        return match(".*token=(.*?);", content).group(1)

    async def get_token(self):
        url = "https://widget.1688.com/front/ajax/bridge.html?target=brg-29352"
        try:
            async with self.__session.get(url, timeout=5) as resp:
                self.__csrf_token = self.match_token(str(resp.cookies))
        except TimeoutError:
            self.status = False
        except ClientConnectionError:
            self.status = False

    async def poll(self):
        url = "https://widget.1688.com/front/ajax/getJsonComponent.json?namespace=TpAddLike&widgetId=TpAddLike&me" \
              "thodName=execute&params=%7B%22bizType%22%3A%22tp_activity_partner_01%22%2C%22formId%22%3A%222911" \
              "55%22%7D&bizType=tp_activity_partner_01&formId=291155&__mbox_csrf_token={}".format(self.__csrf_token)

        headers = {'Referer': 'https://widget.1688.com/front/ajax/bridge.html?target=brg-42883'}

        result = ''
        try:
            async with self.__session.get(url, headers=headers, timeout=5) as resp:
                result = await resp.text()
        except TimeoutError:
            self.status = False
        except ClientConnectionError:
            self.status = False

        if "true" not in result:
            print("投票失败")
            self.status = False

    async def close_session(self):
        await self.__session.close()


async def spider():
    spider_ = AlibbPoll()

    await spider_.get_token()

    # 判断上个请求是否出错
    if not spider_.status:
        await spider_.close_session()
        return

    await spider_.poll()

    # 判断上个请求是否出错
    if not spider_.status:
        await spider_.close_session()
        return

    # 判断投票成功与否
    if not spider_.status:
        await spider_.close_session()
        return

    await spider_.close_session()

    global count
    count += 1


def main():
    tasks = [spider() for x in range(1000)]

    loop = get_event_loop()
    loop.run_until_complete(gather(*tasks))


if __name__ == '__main__':
    while 1:
        start_time = time()
        before = count  # 上一次的数量
        main()
        now = count - before  # 此次成功刷了多少票
        print(f"总计: {count}, 此次成功刷了{now} 次, 用时: {round(time() - start_time, 2)} 秒")
